<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="简介 Core Data是iOS5之后才出现的一个框架，它提供了对象-关系映射(ORM)的功能，即能够将OC对象转化成数据，保存在SQLite数据库文件中，也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间，我们不需要编写任何SQL语句">
<meta property="og:type" content="article">
<meta property="og:title" content="Coredata">
<meta property="og:url" content="http://yoursite.com/2018/04/06/Coredata/index.html">
<meta property="og:site_name" content="Erhqe">
<meta property="og:description" content="简介 Core Data是iOS5之后才出现的一个框架，它提供了对象-关系映射(ORM)的功能，即能够将OC对象转化成数据，保存在SQLite数据库文件中，也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间，我们不需要编写任何SQL语句">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://ws3.sinaimg.cn/large/006tKfTcly1fq2ro3z3crj30oc0kxq42.jpg">
<meta property="og:image" content="https://ws1.sinaimg.cn/large/006tKfTcly1fq33f9295nj30v30dxmzi.jpg">
<meta property="og:image" content="https://ws3.sinaimg.cn/large/006tKfTcly1fq33fkcn2bj30ta0cvdhv.jpg">
<meta property="og:image" content="https://ws3.sinaimg.cn/large/006tKfTcly1fq33ksvr6vj30ac03kaab.jpg">
<meta property="og:image" content="https://ws1.sinaimg.cn/large/006tKfTcly1fq33oqe32ej30jg06x75m.jpg">
<meta property="og:image" content="https://ws2.sinaimg.cn/large/006tKfTcly1fq33pfk1xyj30jg06xgn3.jpg">
<meta property="og:image" content="https://ws4.sinaimg.cn/large/006tKfTcly1fq33q0q028j30jg06iwfr.jpg">
<meta property="og:image" content="https://ws1.sinaimg.cn/large/006tKfTcly1fq33qcov2cj30jg0730u3.jpg">
<meta property="og:updated_time" content="2019-07-19T05:40:06.074Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Coredata">
<meta name="twitter:description" content="简介 Core Data是iOS5之后才出现的一个框架，它提供了对象-关系映射(ORM)的功能，即能够将OC对象转化成数据，保存在SQLite数据库文件中，也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间，我们不需要编写任何SQL语句">
<meta name="twitter:image" content="https://ws3.sinaimg.cn/large/006tKfTcly1fq2ro3z3crj30oc0kxq42.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/04/06/Coredata/"/>





  <title>Coredata | Erhqe</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Erhqe</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/04/06/Coredata/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Erhqe">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/10.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Erhqe">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Coredata</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-04-06T10:49:03+08:00">
                2018-04-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/CoreData/" itemprop="url" rel="index">
                    <span itemprop="name">CoreData</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/04/06/Coredata/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/04/06/Coredata/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><blockquote>
<p><font color="#778899">Core Data是iOS5之后才出现的一个框架，它提供了对象-关系映射(ORM)的功能，即能够将OC对象转化成数据，保存在SQLite数据库文件中，也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间，我们不需要编写任何SQL语句</font><a id="more"></a></p>
</blockquote>
<blockquote>
<p>NSManagedObject 实体管理类</p>
<p>NSEntityDescription 实体描述类</p>
<p>NSManagedObjectContext 数据管理器类</p>
<p>NSPersistentStoreCoorDinator 数据连接器类</p>
<p>NSManagedObjectModel 数据模型类</p>
</blockquote>
<ul>
<li><p><font color="#A52A2A">NSManagedObjec</font> 简单了解就是我们的CoreData模型! CoreData模型都继承NSManagedObjec</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//	一般情况下创建方法</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">init</span>(entity: <span class="type">NSEntityDescription</span>, insertInto context:<span class="type">NSManagedObjectContext</span>?)</span><br></pre></td></tr></table></figure>
</li>
<li><p><font color="#A52A2A">NSEntityDescription</font> 实体描述</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建方法</span></span><br><span class="line"><span class="keyword">open</span> <span class="class"><span class="keyword">class</span> <span class="title">func</span> <span class="title">entity</span>(<span class="title">forEntityName</span> <span class="title">entityName</span>: <span class="title">String</span>, <span class="title">in</span> <span class="title">context</span>: <span class="title">NSManagedObjectContext</span>) -&gt; <span class="title">NSEntityDescription</span>?</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><font color="#A52A2A">NSManagedObjectContext</font> 负责  增 删 改 查</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">enum</span> <span class="title">NSManagedObjectContextConcurrencyType</span> : <span class="title">UInt</span> </span>&#123;</span><br><span class="line"><span class="meta">@available</span>(iOS, introduced: <span class="number">3.0</span>, deprecated: <span class="number">9.0</span>, message: <span class="string">"Use another NSManagedObjectContextConcurrencyType"</span>)</span><br><span class="line">    <span class="keyword">case</span> confinementConcurrencyType	<span class="comment">//弃用</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> privateQueueConcurrencyType <span class="comment">//专用队列并发类型,指定该上下文(Context)与私有调度队列相关联</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> mainQueueConcurrencyType <span class="comment">//主队列并发类型,指定上下文(Context)将与主队列相关联</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//一般用 privateQueueConcurrencyType</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">init</span>(concurrencyType ct: <span class="type">NSManagedObjectContextConcurrencyType</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p><font color="#A52A2A">NSPersistentStoreCoorDinator</font> 这是NSManagedObjectContext的属性,用来管理数据库的位置和名字</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> store = <span class="type">NSPersistentStoreCoordinator</span>(managedObjectModel: model!)</span><br><span class="line"><span class="keyword">let</span> doc = <span class="type">NSSearchPathForDirectoriesInDomains</span>(<span class="type">FileManager</span>.<span class="type">SearchPathDirectory</span>.documentDirectory, <span class="type">FileManager</span>.<span class="type">SearchPathDomainMask</span>.userDomainMask, <span class="literal">true</span>).first</span><br><span class="line"><span class="keyword">let</span> sqliPath = doc?.appendingFormat(<span class="string">"/%@.sqlite"</span>, name)</span><br><span class="line"><span class="keyword">let</span> <span class="number">_</span> = <span class="keyword">try</span>? [store .addPersistentStore(ofType: <span class="type">NSSQLiteStoreType</span>, configurationName: <span class="literal">nil</span>, at: <span class="type">URL</span> (fileURLWithPath: sqliPath!), options: <span class="literal">nil</span>)]</span><br><span class="line"><span class="comment">//上下文就是通过持久化存储协调器来修改底层文件保存的数据</span></span><br><span class="line">context.persistentStoreCoordinator = store</span><br></pre></td></tr></table></figure>
</li>
<li><p><font color="#A52A2A">NSManagedObjectModel</font> 是托管对象模型,表示着CoreData对应的数据实体</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> url = <span class="type">URL</span> (string: <span class="type">Bundle</span>.main.path(forResource: &lt;#建模文件名#&gt;, ofType: <span class="string">"momd"</span>)!)</span><br><span class="line"><span class="keyword">let</span> model = <span class="type">NSManagedObjectModel</span>(contentsOf: url!)</span><br></pre></td></tr></table></figure>
<p>​</p>
</li>
</ul>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><ul>
<li><p>创建项目是勾选 Use Core Data </p>
</li>
<li><p>如果你创建项目时候没有选择  Use Core Data  那么在项目中按Command + N 搜索Data Model 创建</p>
</li>
<li><p>如果你想独立创建建模的话!不推荐创建项目时勾选 Use Core Data </p>
<h4 id="创建实体Entities"><a href="#创建实体Entities" class="headerlink" title="创建实体Entities"></a>创建实体Entities</h4><p><img src="https://ws3.sinaimg.cn/large/006tKfTcly1fq2ro3z3crj30oc0kxq42.jpg" alt=""></p>
<ul>
<li>创建模型文件选中Entites 中的实体在右侧的菜单中Codegen中选择Manual/None</li>
<li>Editor → Create NSManagedObject Subclass..来创建模型文件</li>
</ul>
</li>
</ul>
<h4 id="增删改查"><a href="#增删改查" class="headerlink" title="增删改查"></a>增删改查</h4><ul>
<li><p>获取Context</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> context = (<span class="type">UIApplication</span>.shared.delegate <span class="keyword">as</span>! <span class="type">AppDelegate</span>).persistentContainer.viewContext</span><br></pre></td></tr></table></figure>
</li>
<li><p>曾 </p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> entityDes = <span class="type">NSEntityDescription</span>.entity(forEntityName: <span class="string">"Clothes"</span>, <span class="keyword">in</span>: context)</span><br><span class="line"><span class="keyword">let</span> model = <span class="type">Clothes</span>.<span class="keyword">init</span>(entity: entityDes!, insertInto: context)</span><br><span class="line">model.name = <span class="string">"aaa"</span></span><br><span class="line">model.price = <span class="type">Int64</span>(arc4random() % <span class="number">1000</span> + <span class="number">1</span>)</span><br><span class="line">model.ccc = <span class="string">"NN"</span></span><br><span class="line">dataSrouce.append(model)</span><br><span class="line"><span class="keyword">try</span>? context.save()</span><br></pre></td></tr></table></figure>
</li>
<li><p>删</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">context.delete(model)</span><br><span class="line"><span class="keyword">try</span>? context.save()</span><br></pre></td></tr></table></figure>
</li>
<li><p>条件删除</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> fetch = <span class="type">NSFetchRequest</span>&lt;<span class="type">NSFetchRequestResult</span>&gt;(entityName: <span class="string">"Clothes"</span>)</span><br><span class="line"><span class="keyword">let</span> pre = <span class="type">NSPredicate</span>(format: <span class="string">"price &lt; %d"</span>, <span class="number">300</span>)</span><br><span class="line">        </span><br><span class="line">fetch.predicate = pre</span><br><span class="line"> <span class="keyword">let</span> deleArray = <span class="keyword">try</span>? context.fetch(fetch)</span><br><span class="line"><span class="keyword">for</span> model <span class="keyword">in</span> deleArray! &#123;</span><br><span class="line">    context.delete(model <span class="keyword">as</span>! <span class="type">Clothes</span>)</span><br><span class="line">     dataSrouce.remove(at: dataSrouce.index(of: model <span class="keyword">as</span>! <span class="type">Clothes</span>)!)</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="keyword">try</span>? context.save()</span><br><span class="line"> tableView.reloadData()</span><br></pre></td></tr></table></figure>
</li>
<li><p>改</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> model = dataSrouce[indexPath.row]</span><br><span class="line">model.name = <span class="string">"CC"</span></span><br><span class="line">model.price = <span class="type">Int64</span>(arc4random() % <span class="number">10</span> + <span class="number">1</span>)</span><br><span class="line">tableView.reloadRows(at: [indexPath], with: .top)</span><br><span class="line"><span class="keyword">try</span>? context.save()</span><br></pre></td></tr></table></figure>
</li>
<li><p>查询</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">  <span class="comment">//  查询</span></span><br><span class="line"><span class="keyword">let</span> fetch = <span class="type">NSFetchRequest</span>&lt;<span class="type">NSFetchRequestResult</span>&gt;(entityName: <span class="string">"Clothes"</span>)</span><br><span class="line">        </span><br><span class="line"> <span class="comment">//  排序描述对象</span></span><br><span class="line"><span class="keyword">let</span> sortDes = <span class="type">NSSortDescriptor</span>(key: <span class="string">"price"</span>, ascending: <span class="literal">true</span>)        </span><br><span class="line">fetch.sortDescriptors = [sortDes]        </span><br><span class="line"><span class="comment">//  执行查询</span></span><br><span class="line"><span class="comment">//        let result : NSPersistentStoreRequest</span></span><br><span class="line">  <span class="keyword">do</span> &#123;</span><br><span class="line">     <span class="keyword">let</span> result = <span class="keyword">try</span> context.fetch(fetch)</span><br><span class="line">    <span class="keyword">for</span> model <span class="keyword">in</span> result &#123;</span><br><span class="line">       dataSrouce.append((model <span class="keyword">as</span>! <span class="type">Clothes</span>))</span><br><span class="line">        &#125;</span><br><span class="line">   &#125;<span class="keyword">catch</span>&#123;</span><br><span class="line">        <span class="built_in">print</span>(error)</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="CoreData版本升级"><a href="#CoreData版本升级" class="headerlink" title="CoreData版本升级"></a>CoreData版本升级</h4><ol>
<li><p>选中xcdatamodeld文件 → Editor → Add Model Version → 命名</p>
</li>
<li><p>选中创建的文件在右边的文件菜单中Current中选择最新的版本(也就是刚刚创建的文件)</p>
</li>
<li><p>在刚刚创建的文件中设置新增的属性</p>
</li>
<li><p>Command + N 在CoreData中找到 Mapping Model 点击 Next</p>
</li>
<li><p>选择旧版的文件 → 点击Next, 选择新版的模型文件 → Next, →命名</p>
</li>
<li><p>命名规范 Student_V1.0_To_V1.1</p>
</li>
<li><p>在创建数据连接器方法当中新增一个字典 [NSMigratePersistentStoresAutomaticallyOption : true]</p>
</li>
<li><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> store = <span class="type">NSPersistentStoreCoordinator</span>(managedObjectModel: model!)</span><br><span class="line"><span class="keyword">let</span> <span class="number">_</span> = <span class="keyword">try</span>? [store .addPersistentStore(ofType: <span class="type">NSSQLiteStoreType</span>, configurationName: <span class="literal">nil</span>, at: <span class="type">URL</span> (fileURLWithPath: sqliPath!), options: [<span class="type">NSMigratePersistentStoresAutomaticallyOption</span> : <span class="literal">true</span>])]</span><br></pre></td></tr></table></figure>
</li>
<li><p>删除老版本创建的模型文件重新生成Editor → Create NSManagedObject Subclass..</p>
</li>
</ol>
<h4 id="多表关联"><a href="#多表关联" class="headerlink" title="多表关联"></a>多表关联</h4><ul>
<li>创建多表关联</li>
</ul>
<p><img src="https://ws1.sinaimg.cn/large/006tKfTcly1fq33f9295nj30v30dxmzi.jpg" alt=""></p>
<p><img src="https://ws3.sinaimg.cn/large/006tKfTcly1fq33fkcn2bj30ta0cvdhv.jpg" alt=""></p>
<ul>
<li><p>测试添加和查询</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ViewController</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.viewDidLoad()</span><br><span class="line">        <span class="keyword">let</span> contextClass = setupContextWithModelName(name: <span class="string">"DBGL"</span>)</span><br><span class="line">        <span class="keyword">let</span> entityDes = <span class="type">NSEntityDescription</span>.entity(forEntityName: <span class="string">"ClassRoom"</span>, <span class="keyword">in</span>: contextClass)</span><br><span class="line">        <span class="keyword">let</span> classModel = <span class="type">ClassRoom</span>.<span class="keyword">init</span>(entity: entityDes!, insertInto: contextClass)</span><br><span class="line">        classModel.roomName = <span class="string">"班级"</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">let</span> contextStu = setupContextWithModelName(name: <span class="string">"DBGL"</span>)</span><br><span class="line">        <span class="keyword">let</span> stuEntity = <span class="type">NSEntityDescription</span>.entity(forEntityName: <span class="string">"Student"</span>, <span class="keyword">in</span>: contextStu)</span><br><span class="line">        <span class="keyword">let</span> stu = <span class="type">Student</span>.<span class="keyword">init</span>(entity: stuEntity!, insertInto: contextStu)</span><br><span class="line">        stu.stuName = <span class="string">"学生"</span></span><br><span class="line">        classModel.student?.adding(stu)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">try</span>? contextClass.save()</span><br><span class="line">        <span class="keyword">try</span>? contextStu.save()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">touchesBegan</span><span class="params">(<span class="number">_</span> touches: Set&lt;UITouch&gt;, with event: UIEvent?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">let</span> fetch = <span class="type">NSFetchRequest</span>&lt;<span class="type">NSFetchRequestResult</span>&gt;.<span class="keyword">init</span>(entityName: <span class="string">"Student"</span>)</span><br><span class="line">        <span class="keyword">let</span> context = setupContextWithModelName(name: <span class="string">"DBGL"</span>)</span><br><span class="line">        <span class="keyword">let</span> result = <span class="keyword">try</span>? context.fetch(fetch)</span><br><span class="line">        <span class="keyword">for</span> model <span class="keyword">in</span> result! &#123;</span><br><span class="line">            <span class="keyword">let</span> model = (model <span class="keyword">as</span>! <span class="type">Student</span>)</span><br><span class="line">            <span class="built_in">print</span>(model.stuName)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">ViewController</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">setupContextWithModelName</span><span class="params">(name : String)</span></span> -&gt;<span class="type">NSManagedObjectContext</span>&#123;</span><br><span class="line">        <span class="keyword">let</span> context = <span class="type">NSManagedObjectContext</span>(concurrencyType: .privateQueueConcurrencyType)</span><br><span class="line">        <span class="keyword">let</span> url = <span class="type">Bundle</span>.main.url(forResource: name, withExtension: <span class="string">"momd"</span>)</span><br><span class="line">        <span class="keyword">let</span> model = <span class="type">NSManagedObjectModel</span>(contentsOf: url!)</span><br><span class="line">        <span class="keyword">let</span> store = <span class="type">NSPersistentStoreCoordinator</span>(managedObjectModel: model!)</span><br><span class="line">        <span class="keyword">let</span> doc = <span class="type">NSSearchPathForDirectoriesInDomains</span>(<span class="type">FileManager</span>.<span class="type">SearchPathDirectory</span>.documentDirectory, <span class="type">FileManager</span>.<span class="type">SearchPathDomainMask</span>.userDomainMask, <span class="literal">true</span>).first</span><br><span class="line">        <span class="keyword">let</span> sqliPath = doc?.appendingFormat(<span class="string">"/%@.sqlite"</span>, name)</span><br><span class="line">        <span class="keyword">let</span> <span class="number">_</span> = <span class="keyword">try</span>? [store .addPersistentStore(ofType: <span class="type">NSSQLiteStoreType</span>, configurationName: <span class="literal">nil</span>, at: <span class="type">URL</span> (fileURLWithPath: sqliPath!), options: <span class="literal">nil</span>)]</span><br><span class="line">        context.persistentStoreCoordinator = store</span><br><span class="line">        <span class="keyword">return</span> context</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="删除关联"><a href="#删除关联" class="headerlink" title="删除关联"></a>删除关联</h5><ul>
<li><p>什么是删除关联</p>
<ul>
<li>当两个表进行关联之后,删除其中一个表的数据对另一个表产生的影响</li>
</ul>
</li>
<li><p>怎么添加删除关系</p>
<p><img src="https://ws3.sinaimg.cn/large/006tKfTcly1fq33ksvr6vj30ac03kaab.jpg" alt=""></p>
</li>
<li><p>Nullify<img src="https://ws1.sinaimg.cn/large/006tKfTcly1fq33oqe32ej30jg06x75m.jpg" alt=""></p>
</li>
<li><p>Cascade<img src="https://ws2.sinaimg.cn/large/006tKfTcly1fq33pfk1xyj30jg06xgn3.jpg" alt=""></p>
</li>
<li><p>No Action<img src="https://ws4.sinaimg.cn/large/006tKfTcly1fq33q0q028j30jg06iwfr.jpg" alt=""></p>
</li>
<li><p>Deny <img src="https://ws1.sinaimg.cn/large/006tKfTcly1fq33qcov2cj30jg0730u3.jpg" alt=""></p>
</li>
</ul>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/17/WechatPay/" rel="next" title="WechatPay">
                <i class="fa fa-chevron-left"></i> WechatPay
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/07/WaterLayout/" rel="prev" title="WaterLayout">
                WaterLayout <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/10.png"
                alt="Erhqe" />
            
              <p class="site-author-name" itemprop="name">Erhqe</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">31</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用"><span class="nav-number">2.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建实体Entities"><span class="nav-number">2.1.</span> <span class="nav-text">创建实体Entities</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#增删改查"><span class="nav-number">2.2.</span> <span class="nav-text">增删改查</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreData版本升级"><span class="nav-number">2.3.</span> <span class="nav-text">CoreData版本升级</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多表关联"><span class="nav-number">2.4.</span> <span class="nav-text">多表关联</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#删除关联"><span class="nav-number">2.4.1.</span> <span class="nav-text">删除关联</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Erhqe</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'TiAY2J24ECwQH9uLYsoJpgIK-gzGzoHsz',
        appKey: 'Y9PiVrPXVmfNsv4Aa6cPsADG',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
